import json
import os
import pandas as pd
from my_class.grade_sim import grade_sim
from my_class.plan_grade import plan_grade
from my_json import load_json
from spider_url import province_url

basic_path = str(os.path.dirname(__file__)) + "\\"

map_choose = basic_path + "map_new.json"
map_school = basic_path + "..\\basic_info\\school_id.json"
map_major = basic_path + "..\\major\\major.json"
map_province = province_url.province

school_grade_sim_path = basic_path + "..\\school_grade_sim\\school_grade_sim{id}.json"
school_grade_path = basic_path + "..\\school_grade\\school_grade_{id}.json"
school_plan_path = basic_path + "..\\school_plan\\school_plan_{id}.json"

sim_save_path = basic_path + "sim\\school_grade_sim.csv"
grade_save_path = basic_path + "sim\\school_grade.csv"

map_choose = load_json(map_choose)
print(len(map_choose))
map_school = load_json(map_school)
map_major = load_json(map_major)


def get_major_code(mid):
    try:
        return map_major[mid]["code"]
    except:
        return ""


def subject_sort(subjects):
    if len(subjects) <= 1:
        return subjects
    order = {"物理": 1, "历史": 2, "化学": 3, "政治": 4, "生物": 5, "地理": 6, "技术": 7}
    if not all(subject in order.keys() for subject in subjects):
        raise ValueError()
    return sorted(subjects, key=lambda x: order.get(x, float('inf')))


def get_choose_name(s, type="3"):
    if type == "1":
        d = {"r": ["物理", "化学", "生物"], "n": 0, "o": []}
        return d
    if type == "2":
        d = {"r": ["历史", "政治", "地理"], "n": 0, "o": []}
        return d
    if s == "" or s == "0" or s == "不限":
        d = {"r": [], "n": 0, "o": []}
        return d
    try:
        d = map_choose[s]
        d["r"] = subject_sort(d["r"])
        d["o"] = subject_sort(d["o"])
        return d
    except:
        print(s)
        d = {"r": [], "n": 0, "o": []}
        return d


def choose_to_string(require):
    if require["n"] == 0 and len(require["r"]) == 0:
        return "不限"
    s = ""
    if len(require["r"]) > 0:
        r = require["r"]
        s += "["
        for i in range(len(r)):
            s += r[i] + "、"
        s = s[:-1] + "]必选；"
    if len(require["o"]) > 0:
        o = require["o"]
        s += "["
        for i in range(len(o)):
            s += o[i] + "/"
        s = s[:-1]
        s += "]" + str(len(require["o"])) + "选" + str(require["n"]) + "；"
    return s


def init_sim():
    df = []
    for k_province, province_name in map_province.items():
        print(province_name)
        sim = load_json(school_grade_sim_path.format(id=k_province))
        for k_school, v1_t in map_school.items():
            school_name = v1_t["name"]
            if k_school in sim.keys():
                v1_sim = sim[k_school]
                for k_year, v2_sim in v1_sim.items():
                    if len(v2_sim) > 0:
                        for v3_sim in v2_sim.values():
                            for v4_sim in v3_sim["item"]:
                                gs = grade_sim()
                                try:
                                    gs.min_grade = float(v4_sim["min"])
                                    if gs.min_grade <= 0 or gs.min_grade > 1500:
                                        continue
                                    gs.min_rank = int(v4_sim["min_section"])
                                    if gs.min_rank <= 0:
                                        continue
                                except:
                                    continue
                                gs.province_name = province_name
                                gs.school_name = school_name
                                gs.year = k_year
                                gs.batch_name = v4_sim["local_batch_name"]
                                gs.type_name = v4_sim["zslx_name"]
                                require = get_choose_name(v4_sim["sg_info"], v4_sim["type"])
                                gs.require_json = json.dumps(require, ensure_ascii=False)
                                gs.require_str = choose_to_string(require)
                                dt = gs.to_df()
                                df.append(dt)
    columns = grade_sim().columns
    df = pd.DataFrame(df, columns=columns)
    print("sort")
    df.sort_values(by=["province_name", "school_name", "year", "min_grade"], ignore_index=True, inplace=True)
    df.to_csv(sim_save_path, index=False, encoding="utf_8_sig")


def init():
    columns = plan_grade().columns
    df = pd.DataFrame([], columns=columns)
    for k_province, province_name in map_province.items():
        print(province_name)
        grade = load_json(school_grade_path.format(id=k_province))
        plan = load_json(school_plan_path.format(id=k_province))
        df0 = pd.DataFrame([], columns=columns)
        for k_school, v1_t in map_school.items():
            school_name = v1_t["name"]
            df1 = []
            if k_school in grade:
                v1_grade = grade[k_school]
                for k_year, v2_grade in v1_grade.items():
                    for v3_grade in v2_grade.values():
                        for v4_grade in v3_grade["item"]:
                            pg = plan_grade()
                            try:
                                pg.min_grade = float(v4_grade["min"])
                                if pg.min_grade <= 0 or pg.min_grade > 1500:
                                    continue
                                pg.min_rank = int(v4_grade["min_section"])
                                if pg.min_rank <= 0:
                                    continue
                            except:
                                continue
                            if v4_grade["spname"] == "":
                                continue
                            pg.school_name = school_name
                            pg.year = k_year
                            pg.province_name = province_name
                            pg.major_name = v4_grade["spname"]
                            pg.batch_name = v4_grade["local_batch_name"]
                            pg.type_name = v4_grade["zslx_name"]
                            pg.level1_name = v4_grade["level1_name"]
                            pg.level2_name = v4_grade["level2_name"]
                            pg.level3_name = v4_grade["level3_name"]
                            pg.special_code = get_major_code(v4_grade["spe_id"])
                            pg.is_grade = 1
                            if v4_grade["sg_info"] == "":
                                require = get_choose_name(v4_grade["sp_info"], v4_grade["type"])
                            else:
                                require = get_choose_name(v4_grade["sg_info"], v4_grade["type"])
                            pg.require_json = json.dumps(require, ensure_ascii=False)
                            pg.require_str = choose_to_string(require)
                            try:
                                pg.max_grade = float(v4_grade["max"])
                            except:
                                pg.max_grade = 0
                            try:
                                pg.avg_grade = float(v4_grade["average"])
                            except:
                                pg.avg_grade = 0
                            pg = pg.to_df()
                            df1.append(pg)
            df1 = pd.DataFrame(df1, columns=columns)
            df1.drop_duplicates(inplace=True, ignore_index=True)
            df2 = []
            if k_school in plan:
                for k_year, v2_plan in plan[k_school].items():
                    for v3_plan in v2_plan.values():
                        for v4_plan in v3_plan["item"]:
                            try:
                                num = int(v4_plan["num"])
                                if num <= 0:
                                    continue
                            except:
                                continue
                            code = ""
                            if "spcode" in v4_plan and v4_plan["spcode"] != "" and v4_plan["spcode"] != "0":
                                code = v4_plan["spcode"]
                            elif "spe_id" in v4_plan and v4_plan["spe_id"] != "" and v4_plan["spe_id"] != "0":
                                code = get_major_code(v4_plan["spe_id"])
                            dft = df1.loc[
                                (df1["province_name"] == province_name) & (df1["school_name"] == school_name) & (
                                        df1["year"] == k_year)]
                            if len(dft) > 0:
                                if code != "":
                                    dft = dft.loc[
                                        (dft["special_code"] == code) | (dft["major_name"] == v4_plan["spname"])]
                                else:
                                    dft = dft.loc[dft["major_name"] == v4_plan["spname"]]
                                if len(dft) > 0:
                                    dft.loc[:, "num_student"] = num
                                    dft.loc[:, "is_plan"] = 1
                                    continue
                            pg = plan_grade()
                            pg.province_name = province_name
                            pg.school_name = school_name
                            pg.year = k_year
                            pg.major_name = v4_plan["spname"]
                            pg.batch_name = v4_plan["local_batch_name"]
                            pg.type_name = v4_plan["zslx_name"]
                            pg.level1_name = v4_plan["level1_name"]
                            pg.level2_name = v4_plan["level2_name"]
                            pg.level3_name = v4_plan["level3_name"]
                            pg.special_code = code
                            pg.num_student = num
                            pg.is_plan = 1
                            if v4_plan["sg_info"] == "":
                                require = get_choose_name(v4_plan["sp_info"], v4_plan["type"])
                            else:
                                require = get_choose_name(v4_plan["sg_info"], v4_plan["type"])
                            pg.require_json = json.dumps(require, ensure_ascii=False)
                            pg.require_str = choose_to_string(require)
                            pg = pg.to_df()
                            df2.append(pg)
            df2 = pd.DataFrame(df2, columns=columns)
            df2.drop_duplicates(inplace=True, ignore_index=True)
            df0 = pd.concat([df0, df1, df2], ignore_index=True)
        df = pd.concat([df, df0], ignore_index=True)
    print("sort")
    df.sort_values(by=["province_name", "school_name", "year", "min_grade"], ignore_index=True, inplace=True)
    df.to_csv(grade_save_path, index=False, encoding="utf_8_sig")

